package com.app.service;

import java.util.ArrayList;

import com.app.model.AlarmDataManager;
import com.app.model.AlarmDataManager.AlarmLoader;
import com.app.util.ApplicationMediator;
import com.app.util.MessageListenerAdapter;
import com.app.util.VolumeManager;
import com.app.view_controller.ContentActivity;

import android.R;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.util.Log;
import android.widget.Toast;

@SuppressWarnings("unused")
public class VolumeChangedReceiver extends BroadcastReceiver {

	private static final String TAG = "VOLUME_CHANGED_RECEIVER";
	private static final boolean DEBUG = true;
	private Context mContext;

	public VolumeChangedReceiver() {
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (DEBUG)
			Log.d(TAG, ""+TAG+" called");
		mContext = context;
		VolumeManager mVolume = VolumeManager.getVolumeManagerInstance(context);
		mVolume.saveDefaultVolumeLevels(false);
		if (mVolume.areVolumesSafe())
			new Runnable() {

				@Override
				public void run() {
					ArrayList<AlarmDataManager> mList = AlarmLoader.getStoredAlarmList(mContext);
					boolean hasAnAlarmBeenModified = false;
					for (int i = 0; i < mList.size(); i++) {
						AlarmDataManager alarm = mList.get(i);
						if (alarm.isAlarmEneable() && (alarm.isControlNotificationEneable() || alarm.isControlRingtoneEneable())) {
							Toast.makeText(mContext, mContext.getResources().getString(com.app.alarm.R.string.VolumeChangedReceiver_warning_toast),
									Toast.LENGTH_SHORT).show();
							alarm.setControlNotificationEneable(false);
							alarm.setControlRingtoneEneable(false);
							if (DEBUG)
								Log.d(TAG, "Set control ringtone to false for the alarm" + alarm.getAlarmId());
							hasAnAlarmBeenModified = true;
							alarm.savetoStorage();
						}
					}
					if (hasAnAlarmBeenModified) { //TODO Better use a broadcast receiver
						if (DEBUG)
							Log.d(TAG, "Update alarmlist and dialog called");
						ApplicationMediator.getInstance().sendMessage(ContentActivity.UPDATE_ALARMLIST_AND_DIALOG);
					}
				}
			}.run();
		mVolume.decreaseCounter();
	}

}
